<?php

/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.phperskill.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */

namespace App\User;

use \App\Facade;

/**
 * PSE用户中心公共模块
 * @author LazyPHP
 * @version 1.0
 */
class Common extends Facade {

    public function __construct() {
        parent::__construct();
        $this->isLogin();
    }

    /**
     * 验证邮箱是否已经存在
     */
    protected function checkMail($value) {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $this->error('请输入正确的电子邮箱');
        }
        $result = $this->checkUserDbOpera($value, 'mail');
        if (!empty($result)) {
            $this->error('邮箱已经存在!');
        }
    }

    /**
     * 验证账号是否已经存在
     */
    protected function checkAccount($value) {
        $result = $this->checkUserDbOpera($value, 'account');
        if (!empty($result)) {
            $this->error('登陆账号已存在!');
        }
    }

    /**
     * 验证用户名是否已经存在
     */
    protected function checkNickname($value) {
        $result = $this->checkUserDbOpera($value, 'nickname');
        if (!empty($result)) {
            $this->error('用户名已存在!');
        }
    }

    /**
     * 验证电话号码是否已经存在
     */
    protected function checkTel($value) {
        $result = $this->checkUserDbOpera($value, 'tel');
        if (!empty($result)) {
            $this->error('手机号码已经存在!');
        }
    }

    /**
     * 用户表操作
     * @param type $value 检查的值
     * @param type $type 查找字段
     * @return boolean
     */
    protected function checkUserDbOpera($value, $field) {
        $db = self::db('user');
        $data[$field] = $value;
        $where = '';

        if (!empty($_SESSION['user']['uid'])) {
            $where = " and uid != {$_SESSION['user']['uid']}";
        }

        $result = $db->where("{$field} = :{$field}{$where}")->find($data);
        if (empty($result)) {
            return false;
        }
        return $result;
    }

}
